#!/usr/bin/env bash
#
# curl -SsL https://raw.githubusercontent.com/Xiechengqi/scripts/refs/heads/master/install/Agent/agent -o /usr/local/bin/agent && chmod +x /usr/local/bin/agent
#
source ~/.profile

export GITHUB_PROXY="https://gh-proxy.com"
export BASEURL="${GITHUB_PROXY}/https://raw.githubusercontent.com/Xiechengqi/scripts/refs/heads/master/install/Agent"

cat << EOF

-------------------------------------------------------------------------------------------------
|                                        agent                                                  |
| 更新命令: agent update                                                                        |
-------------------------------------------------------------------------------------------------

EOF

if [ "${@}" = "update" ]
then
if sudo curl -SsL ${BASEURL}/agent -o /usr/local/bin/agent && sudo chmod +x /usr/local/bin/agent
then
echo "===== 更新成功 ====="
else
echo "===== 更新失败，手动更新命令: curl -SsL ${BASEURL}/agent -o /usr/local/bin/agent ====="
fi
exit 0
fi

if [ "${@}" = "clean" ]
then
echo "===== 清理 ~/.profile 中 ENV ====="
sed -i '/OPENAI_API_BASEURL/d;/OPENAI_MODEL/d;/OPENAI_API_KEY/d' ~/.profile
fi

! which jq &> /dev/null && echo "Please install jq first, exit ..." && exit 1

! which agent &> /dev/null && sudo curl -SsL ${BASEURL}/agent -o /usr/local/bin/agent && sudo chmod +x /usr/local/bin/agent

if [ ".${OPENAI_API_BASEURL}" = "." ]
then
read -p "OPENAI_API_BASEURL(eg: https://openrouter.ai/api/v1): " OPENAI_API_BASEURL
[ ".${OPENAI_API_BASEURL}" = "." ] && echo "OPENAI_API_BASEURL can not be empty, exit ..." && exit 1 || echo "export OPENAI_API_BASEURL=\"${OPENAI_API_BASEURL}\"" >> ~/.profile
fi

if [ ".${OPENAI_MODEL}" = "." ]
then
read -p "OPENAI_MODEL(eg: deepseek/deepseek-r1): " OPENAI_MODEL
[ ".${OPENAI_MODEL}" = "." ] && echo "OPENAI_MODEL can not be empty, exit ..." && exit 1 || echo "export OPENAI_MODEL=\"${OPENAI_MODEL}\"" >> ~/.profile
fi

if [ ".${OPENAI_API_KEY}" = "." ]
then
read -p "OPENAI_API_KEY(eg: sk...): " OPENAI_API_KEY
[ ".${OPENAI_API_KEY}" = "." ] && echo "OPENAI_API_KEY can not be empty, exit ..." && exit 1 || echo "export OPENAI_API_KEY=\"${OPENAI_API_KEY}\"" >> ~/.profile
fi

INIT_DATA=$(cat << EOF
{
  "model": "${OPENAI_MODEL}",
  "messages": [
    {"role": "user", "content": "$@，如果完成当前tool_calls中所有tool调用，就能回答用户问题，则在最后调用一次 terminate tool"}
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定地点今天天气",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "城市英文名称，例如 Beijing、Shanghai"
            }
          },
          "required": ["location"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_linux_command_context",
        "description": "获取指定Linux命令运行上下文",
        "parameters": {
          "type": "object",
          "properties": {
            "command": {
              "type": "string",
              "description": "Linux命令，例如 ls -alht /root"
            }
          },
          "required": ["command"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_url_context",
        "description": "获取指定URL内容",
        "parameters": {
          "type": "object",
          "properties": {
            "url": {
              "type": "string",
              "description": "URL 链接，例如 https://google.com"
            }
          },
          "required": ["url"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_file_content",
        "description": "获取本地文件内容",
        "parameters": {
          "type": "object",
          "properties": {
            "file_path": {
              "type": "string",
              "description": "文件路径，例如 main.py 或 /root/test.sh"
            }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_token_market_data",
        "description": "获取指定加密货币市场行情数据",
        "parameters": {
          "type": "object",
          "properties": {
            "token": {
              "type": "string",
              "description": "加密货币 token，例如 BTCUSDT"
            }
          },
          "required": ["token"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "terminate",
        "description": "任务完成"
      }
    }
  ],
  "tool_choice": "auto"
}
EOF
)
curl -SsL ${OPENAI_API_BASEURL}/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${OPENAI_API_KEY}" \
  -d "${INIT_DATA}" 2> /dev/null | grep -E -v '^$' > /tmp/llm.log

echo "===== Reasoning ====="
cat /tmp/llm.log | jq -r '.choices[0].message.reasoning'

rm -f /tmp/llm-step.log
if [ "$(cat /tmp/llm.log | jq -r .choices[0].message.tool_calls)" = "null" ] || [ "$(cat /tmp/llm.log | jq -r .choices[0].message.tool_calls[0].function.name)" = "terminate" ]
then

echo
echo "===== 不需要调用 Tool ====="
echo

else

echo "===== Function ====="
cat /tmp/llm.log | jq -r '.choices[0].message.tool_calls[].function'

for step in $(cat /tmp/llm.log | jq -r '.choices[0].message.tool_calls[].index')
do
rm -f /tmp/llm-step-${step}.log
echo "======= Step ${step} =======" >> /tmp/llm-step-${step}.log
TOOL=$(cat /tmp/llm.log | jq --arg STEP "${step}" -r '.choices[0].message.tool_calls[$STEP | tonumber].function.name')
OPTS=$(cat /tmp/llm.log | jq --arg STEP "${step}" -r '.choices[0].message.tool_calls[$STEP | tonumber].function.arguments | fromjson | to_entries | map("\(.key)=\(.value)") | join(" ")')
[ "${TOOL}" = "terminate" ] && echo && echo "===== 已经可以回答用户提问，调用 Tools 结束 =====" && echo && rm -f /tmp/llm-step-${step}.log && break
export cmd="bash <(curl -SsL ${BASEURL}/${TOOL}.sh) ${OPTS} </dev/tty"
[ ".${cmd}" != "." ] && echo "=> ${cmd}" && eval ${cmd} >> /tmp/llm-step-${step}.log
cat /tmp/llm-step-${step}.log | grep -E -v '^$' >> /tmp/llm-step.log
cat /tmp/llm-step-${step}.log
done

fi

echo "用户原始提问内容: $@" >> /tmp/llm-step.log

echo "===== 原始提问: $@ ====="

# 总结
CONTENT=$(cat /tmp/llm-step.log | jq -Rs .)

DATA=$(cat << EOF
{
  "model": "${OPENAI_MODEL}",
  "messages": [
  {"role": "user", "content": ${CONTENT}}
  ]
}
EOF
)

echo "===== 最终回答 ====="
curl -SsL ${OPENAI_API_BASEURL}/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${OPENAI_API_KEY}" \
  -d "${DATA}" | jq -r .choices[0].message.content
